import type { FC } from "react";
import type { ChatMessage } from "../types/chat";
import MessageContent from "./MessageContent";
import MessageSkeleton from "./MessageSkeleton";
import RobotIcon from "../assets/robot.svg";
import Avatar from "./ui/Avatar";
import userService from "../utils/userService";
import { useState, useEffect } from "react";

interface MessageListProps {
  messages: ChatMessage[];
  /** 是否正在接收流式响应 */
  isStreaming?: boolean;
  /** 是否正在加载（等待服务器首次响应） */
  isLoading?: boolean;
}

/**
 * 消息列表组件
 *
 * 渲染聊天消息列表，包括用户消息和助手回复
 * 支持显示打字机效果的流式响应
 * 支持在AI响应前显示骨架屏
 */
const MessageList: FC<MessageListProps> = ({
  messages,
  isStreaming = false,
  isLoading = false,
}) => {
  // 用户登录状态和头像
  const [isLoggedIn, setIsLoggedIn] = useState(userService.isLoggedIn);
  const [avatarUrl, setAvatarUrl] = useState(
    userService.userInfo?.avatar || null
  );

  // 监听用户状态变化
  useEffect(() => {
    const unsubscribe = userService.subscribe(() => {
      setIsLoggedIn(userService.isLoggedIn);
      setAvatarUrl(userService.userInfo?.avatar || null);
    });

    return unsubscribe;
  }, []);

  // 如果没有消息，显示开始聊天提示
  if (!messages || messages.length === 0) {
    return (
      <div className="h-full flex flex-col items-center justify-center text-center p-4">
        <h2 className="text-xl font-medium text-[#1296db] dark:text-gray-300 mb-2">
          开始一个新对话
        </h2>
        <p className="text-sm text-gray-500 dark:text-gray-400 max-w-md">
          发送一条消息开始聊天。您可以询问任何问题，我将尽力提供帮助。
        </p>
      </div>
    );
  }

  // 检查是否应该显示骨架屏
  // 条件：正在加载 或 (正在流传输 且 最后一条消息是空的占位消息)
  const shouldShowSkeleton =
    isLoading ||
    (isStreaming &&
      messages.length > 0 &&
      messages[messages.length - 1].role === 1 &&
      (!messages[messages.length - 1].content ||
        messages[messages.length - 1].content.trim() === "") &&
      messages[messages.length - 1].isPlaceholder);

  return (
    <div className="pt-4 pb-1 md:pt-6 md:pb-2">
      {messages && messages.length > 0 && (
        <div className="space-y-4 md:space-y-6">
          {messages.map((msg, index) => {
            // 如果是最后一条消息且应该显示骨架屏，则跳过渲染这条消息
            if (
              index === messages.length - 1 &&
              shouldShowSkeleton &&
              msg.role === 1
            ) {
              return null;
            }

            return (
              <div
                key={index}
                className={`flex ${
                  msg.role === 0
                    ? "justify-end"
                    : msg.role === 2
                    ? "justify-center"
                    : "justify-start"
                }`}
              >
                {msg.role === 1 && (
                  <div className="w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center mr-2 mt-1 flex-shrink-0">
                    <img src={RobotIcon} alt="AI" className="h-10 w-10" />
                  </div>
                )}
                {msg.role === 2 && (
                  <div className="w-8 h-8 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center mr-2 mt-1 flex-shrink-0">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-5 w-5 text-amber-600 dark:text-amber-400"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={1.5}
                        d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"
                      />
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={1.5}
                        d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                      />
                    </svg>
                  </div>
                )}
                <div
                  className={`rounded-lg px-4 py-2 max-w-[90%] md:max-w-[85%] lg:max-w-[90%] shadow-sm ${
                    msg.role === 0
                      ? "bg-blue-500 text-white"
                      : msg.role === 2
                      ? "bg-amber-100 dark:bg-amber-900/30 text-amber-800 dark:text-amber-200 max-w-3xl mx-auto text-sm"
                      : "bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200"
                  }`}
                >
                  <div
                    className={`${
                      msg.isPlaceholder && !msg.content
                        ? "opacity-0"
                        : "opacity-100"
                    } transition-opacity whitespace-pre-wrap`}
                  >
                    <MessageContent
                      message={msg}
                      allowHtml={msg.role === 1}
                      isStreaming={isStreaming && msg.isPlaceholder}
                    />
                  </div>
                </div>
                {msg.role === 0 && (
                  <div className="ml-2 mt-1 flex-shrink-0">
                    {isLoggedIn ? (
                      <Avatar
                        src={avatarUrl}
                        size="md"
                        alt={userService.userInfo?.nickname || "用户头像"}
                      />
                    ) : (
                      <div className="w-10 h-10 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          className="h-5 w-5 text-gray-600 dark:text-gray-400"
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={1.5}
                            d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"
                          />
                        </svg>
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}

          {/* 如果应该显示骨架屏，添加骨架屏 */}
          {shouldShowSkeleton && <MessageSkeleton lines={3} />}

          {/* 添加一个不可见的底部锚点元素，便于滚动到底部 */}
          <div id="chat-bottom-anchor" className="h-1" />
        </div>
      )}
    </div>
  );
};

export default MessageList;
